package com.touzbi.hss.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;

import com.touzbi.hss.beans.Patient;

public class PatientDAO implements AbstractPatientDAO {

	private static final String HIBERNATE_LIST_QUERY = "from Patient";
	private static final String HIBERNATE_RESULT_QUERY = "from Patient patient where patient.firstName like ?";
	private static final String HIBERNATE_PATIENT_QUERY = "from Patient where id=?";

	private static final String EXCEPTION_NO_PATIENT = "No patient found";

	private Session session;

	public PatientDAO(Session session) {
		this.session = session;
	}

	@Override
	public List getPatientList() {
		List result = this.session.createQuery(HIBERNATE_LIST_QUERY).list();
		if (result == null) {
			result = new ArrayList<>();
		}
		return result;
	}

	@Override
	public void addPatient(Patient patient) {
		this.session.save(patient); //TODO
	}

	@Override
	public List getQueryResult(String query) throws Exception {
		List result = this.session.createQuery(HIBERNATE_RESULT_QUERY)
				.setParameter(0, "%" + query + "%").list();
		if (result == null || result.isEmpty()) {
			throw new Exception(EXCEPTION_NO_PATIENT);
		}
		return result;
	}

	@Override
	public List<String> getListColumn() {

		List<String> list = new ArrayList<String>();
		//TODO getListColumn hibernate style

		//		Connection connection = this.daoFactory.getConnection();
		//		try {
		//			PreparedStatement ps = connection
		//					.prepareStatement(LIST_COLUMN_QUERY);
		//			ResultSetMetaData rsmd = ps.getMetaData();
		//			String columnName;
		//			for (int i = 1; i <= rsmd.getColumnCount(); i++) {
		//				columnName = rsmd.getColumnName(i);
		//				if (!columnName.equals("P_Id")) {
		//					list.add(columnName);
		//				}
		//			}
		//		} catch (SQLException e) {
		//			e.printStackTrace();
		//		} finally {
		//			try {
		//				connection.close();
		//			} catch (SQLException e) {
		//			}
		//		}
		//TODO get list colomn in DAO
		return list;
	}

	@Override
	public Patient getPatientById(long id) {
		return (Patient) this.session.createQuery(HIBERNATE_PATIENT_QUERY)
				.setParameter(0, id).uniqueResult();
	}
}
